<template>
  <a-modal @cancel="close" title="行驶证记录" width="45vw" :visible="visible" unmount-on-close>
    <div class="insure-edit-content">
      <page-form :model="form" ref="formRef" layout="vertical">
        <card
          :title="item.label"
          v-for="(item, index) in form.driveLicenseRecordList"
          :key="item.label"
          :showDivider="index == form.driveLicenseRecordList.length - 1 ? false : true"
        >
          <page-form-row :gutter="24">
            <page-form-item :label="`${item.label}时间`" prop="driveLicenseUseTime" size="1/2">
              <i-date-picker v-model="item.driveLicenseUseTime" style="width: 100%" show-time format="YYYY-MM-DD HH:mm:ss" />
            </page-form-item>
            <page-form-item :label="item.name" prop="depositState" size="1/2">
              <a-select v-model="item.depositState" :placeholder="`请选择${item.name}`" allow-clear>
                <a-option :value="1">是</a-option>
                <a-option :value="2">否</a-option>
              </a-select>
            </page-form-item>
            <page-form-item label="押金金额" prop="depositAmount" size="1/2">
              <i-input-number v-model="item.depositAmount" :precision="0" :max="9999999999" />
            </page-form-item>
            <page-form-item label="上传凭证" prop="fileIdList" size="1/2">
              <upload-img v-model="item.fileIdList" limit="1" @change="(val) => onChange(item, val)" />
            </page-form-item>
          </page-form-row>
        </card>
      </page-form>
    </div>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="saveFn" :loading="loading">确认</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { addDrivingRecord } from '@/api/asset/carViolation'
  import { cloneDeep } from 'lodash-es'

  // emit 事件
  const emit = defineEmits(['ok'])
  const visible = ref(false)

  const form = ref<any>({
    driveLicenseRecordList: [
      {
        label: '行驶证借出',
        name: '是否收取押金',
        driveLicenseUseState: 1,
        driveLicenseUseTime: '',
        depositState: null,
        depositAmount: null,
        fileIdList: [],
      },
      {
        label: '行驶证归还',
        name: '是否归还押金',
        driveLicenseUseState: 2,
        driveLicenseUseTime: '',
        depositState: null,
        depositAmount: null,
        fileIdList: [],
      },
    ],
  })
  const formRef = ref()
  const loading = ref(false)

  const open = (record: any) => {
    visible.value = true
    console.log('record', record)
    const cloneRecord = cloneDeep(record)

    // 兼容旧数据，防止没有字段或者字段长度不够
    if (!cloneRecord.driveLicenseRecordList || cloneRecord.driveLicenseRecordList.length < 2) {
      cloneRecord.driveLicenseRecordList = form.value.driveLicenseRecordList
    }
    // ---------------------------------

    // 覆盖对应的值
    cloneRecord.driveLicenseRecordList.forEach((newRecord: any) => {
      const index = form.value.driveLicenseRecordList.findIndex((item: any) => item.driveLicenseUseState === newRecord.driveLicenseUseState)
      if (index !== -1) {
        form.value.driveLicenseRecordList[index] = {
          ...form.value.driveLicenseRecordList[index],
          driveLicenseUseTime: newRecord.driveLicenseUseTime,
          depositState: newRecord.depositState,
          depositAmount: newRecord.depositAmount,
          fileIdList: newRecord.fileIdList,
        }
      }
    })

    cloneRecord.driveLicenseRecordList = form.value.driveLicenseRecordList

    form.value = { ...cloneRecord }
    console.log('form', form.value)
  }

  // 关闭
  const close = () => {
    visible.value = false
    form.value = {
      driveLicenseRecordList: [
        {
          label: '行驶证借出',
          name: '是否收取押金',
          driveLicenseUseState: 1,
          driveLicenseUseTime: '',
          depositState: null,
          depositAmount: null,
          fileIdList: [],
        },
        {
          label: '行驶证归还',
          name: '是否归还押金',
          driveLicenseUseState: 2,
          driveLicenseUseTime: '',
          depositState: null,
          depositAmount: null,
          fileIdList: [],
        },
      ],
    }
  }

  const saveFn = () => {
    loading.value = true

    formRef.value.validate((valid: boolean) => {
      if (!valid) {
        console.log('form: ', form.value)

        addDrivingRecord({ id: form.value.id, driveLicenseRecordList: form.value.driveLicenseRecordList })
          .then(() => {
            emit('ok')
            close()
          })
          .catch((error: any) => {
            console.log('error: ', error)
          })
          .finally(() => {
            loading.value = false
          })
      }
    })
  }

  const onChange = (item: any, val: any) => {
    console.log('item', item, val)
    item.fileIdList = val

    if (!val || val.length < 0) {
      item.fileIds = null
    }
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  .insure-edit-content {
    overflow-x: hidden;
    max-height: 80vh;
  }
</style>
